package com.example.lib.utils

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import com.example.lib.LibApp
import com.example.lib.R

/**
 *
 * Description: Toast工具类
 * 防止吐司重复展示
 */
object ToastUtils {
    private var oldMsg: String? = null
    private var toast: Toast? = null
    private val mHandler = Looper.getMainLooper()?.let {
        Handler(it)
    }

    /**
     * 吐Toast
     */
    fun showToast(content: String) {
        mHandler?.post {
            toast(content)
        }
    }

    /**
     * 吐Toast
     */
    fun delayedShowToast(content: String, time: Long) {
        mHandler?.postDelayed({
            toast(content)
        }, time)
    }

    @SuppressLint("InflateParams")
    private fun toast(content: String) {
        toast?.let {
            if (content == oldMsg) {
                it.setGravity(Gravity.CENTER, 0, 40)
                it.show()
            } else {
                oldMsg = content
                (it.view as TextView).text = content
                it.setGravity(Gravity.CENTER, 0, 40)
                it.show()
            }
        } ?: let {
            val inflater = LibApp.appContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            val textView = inflater.inflate(R.layout.layout_toast, null, false) as TextView
            toast = Toast(LibApp.appContext)
            toast?.let {
                it.view = textView
                textView.text = content
                it.setGravity(Gravity.CENTER, 0, 40)
                it.show()
            }
        }
    }
}